import Core.WindFunctions as Wind
import Core.Config as Config
import Core.Gadget as Gadget
import DataProcess
import numpy as np
import pandas as pd
from datetime import timedelta, datetime


def Request_HistoricalIndustry(database, symbols, tradeDate, standard="1", level="1"):
    # ---Field----
    contents = [];
    contents.append("industry2")

    # ---Necessary Parameters---
    params = {}
    datestr = Gadget.ToDateString(tradeDate)
    params["tradeDate"] = datestr
    params["industryType"] = standard  # 1:申万行业  2:Wind行业  3:中信行业
    params["industryStandard"] = level

    # ---Request Functions---
    valuesBySymbol = Wind.WSS(symbols, contents, params)
    # values = WSS(symbols, contents, params)[0]
    return valuesBySymbol


#---获取 行业，支持多symbols---
def Request_Write_HistoricalIndustry(database, symbols, tradeDate):
    #
    stdDateTime = Gadget.ToUTCDateTime(tradeDate)
    stdDateTime = stdDateTime + timedelta(days=1)

    #---SW Industry---
    swValuesBySymbol1 = Request_HistoricalIndustry(database, symbols, tradeDate, standard="1", level="1")
    swValuesBySymbol2 = Request_HistoricalIndustry(database, symbols, tradeDate, standard="1", level="2")
    swValuesBySymbol3 = Request_HistoricalIndustry(database, symbols, tradeDate, standard="1", level="3")

    #---CS Industry---
    csValuesBySymbol1 = Request_HistoricalIndustry(database, symbols, tradeDate, standard="3", level="1")
    csValuesBySymbol2 = Request_HistoricalIndustry(database, symbols, tradeDate, standard="3", level="2")
    csValuesBySymbol3 = Request_HistoricalIndustry(database, symbols, tradeDate, standard="3", level="3")

    #
    valuesBySymbol = []
    valuesBySymbol.append(swValuesBySymbol1)
    valuesBySymbol.append(swValuesBySymbol2)
    valuesBySymbol.append(swValuesBySymbol3)
    valuesBySymbol.append(csValuesBySymbol1)
    valuesBySymbol.append(csValuesBySymbol2)
    valuesBySymbol.append(csValuesBySymbol3)

    #
    for i in range(len(symbols)):
        #
        symbol = symbols[i]
        #---Upsert to Database---
        dataSeriesSWIndustry1 = DataSeries.DataSeries(symbol + "_SWIndustry_Factor")
        dataSeriesSWIndustry2 = DataSeries.DataSeries(symbol + "_SWIndustry2_Factor")
        dataSeriesSWIndustry3 = DataSeries.DataSeries(symbol + "_SWIndustry3_Factor")
        dataSeriesCSIndustry1 = DataSeries.DataSeries(symbol + "_CSIndustry_Factor")
        dataSeriesCSIndustry2 = DataSeries.DataSeries(symbol + "_CSIndustry2_Factor")
        dataSeriesCSIndustry3 = DataSeries.DataSeries(symbol + "_CSIndustry3_Factor")
        #
        dataSeries = []
        dataSeries.append(dataSeriesSWIndustry1)
        dataSeries.append(dataSeriesSWIndustry2)
        dataSeries.append(dataSeriesSWIndustry3)
        dataSeries.append(dataSeriesCSIndustry1)
        dataSeries.append(dataSeriesCSIndustry2)
        dataSeries.append(dataSeriesCSIndustry3)

        #
        document = {}
        document["Symbol"] = symbol
        document["StdDateTime"] = stdDateTime

        documents = []
        documents.append(copy.deepcopy(document))
        documents.append(copy.deepcopy(document))
        documents.append(copy.deepcopy(document))
        documents.append(copy.deepcopy(document))
        documents.append(copy.deepcopy(document))
        documents.append(copy.deepcopy(document))

        for j in range(len(valuesBySymbol)):
            value = valuesBySymbol[j][i]["industry2"]
            #
            if value != None:
                documents[j]["Value"] = value
                dataSeries[j].Add(documents[j])
                #---Save to Database---
                database.SaveDataSeries(dataSeries[j])
        kkwood = 1
    kkwood = 0


# ---适应MySql的新版本---
def Request_Write_HistoricalIndustry2(database, symbols, tradeDate):

    def Request_HistoricalIndustry_InSum(database, symbols, tradeDate, standard):
        industryList1 = Request_HistoricalIndustry(database, symbols, tradeDate, standard, level="1")
        industryList2 = Request_HistoricalIndustry(database, symbols, tradeDate, standard, level="2")
        industryList3 = Request_HistoricalIndustry(database, symbols, tradeDate, standard, level="3")
        #
        documents = []
        for i in range(len(symbols)):
            symbol = symbols[i]
            document = {}
            document["Symbol"] = symbol
            # 1:申万行业  2:Wind行业  3:中信行业
            document["Type"] = "NA"
            if standard == "1":
                document["Type"] = "SW"
            elif standard == "3":
                document["Type"] = "Citic"
            #
            document["DateTime"] = tradeDate
            document["Date"] = tradeDate.date()
            document["Industry"] = industryList1[i]["industry2"]
            document["Industry2"] = industryList2[i]["industry2"]
            document["Industry3"] = industryList3[i]["industry2"]
            #
            document["Key2"] = symbol + "_" + Gadget.ToDateString(tradeDate) + "_" + document["Type"]
            documents.append(document)
        #
        database.Upsert_Many("Stock", "Industry", [], documents)
        a = 0

    # ---SW Industry---
    # Request_HistoricalIndustry_InSum(database, symbols, tradeDate, standard="1")
    # ---Citic Industry---
    Request_HistoricalIndustry_InSum(database, symbols, tradeDate, standard="3")


#
def Batch_Download_HistoricalIndustry(database, datetime1, datetime2, instruments=[]):
    releaseDates = Gadget.GenerateReleaseDates(datetime1, datetime2)
    #
    if len(instruments) == 0:
        instruments = database.Find("Instruments", "Stock")
    #
    DataProcess.Download_Data_MultSymbols(database, instruments, releaseDates, Request_Write_HistoricalIndustry2)


if __name__ == '__main__':
    #
    config = Config.Config()
    database = config.DataBase("MySQL")

    Wind.w.start()

    # ---更新行业信息---
    datetime1 = datetime(2000,1,1)
    datetime2 = datetime(2019,9,1)
    Batch_Download_HistoricalIndustry(database, datetime1, datetime2)